
package cn.edu.tsinghua.hpc.gsmsensor;

import cn.edu.tsinghua.hpc.gsmtest.utils.LocationUtils;

import org.apache.http.util.EncodingUtils;

import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.TabActivity;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.TabHost;

import java.io.FileInputStream;
import java.io.FileOutputStream;

public class GSMTesterActivity extends TabActivity {
    private static final String TAG = "GSMTesterActivity";

    private NotificationManager mNM;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        final TabHost tabHost = getTabHost();

        tabHost.addTab(tabHost.newTabSpec("tab1").setIndicator(getString(R.string.state))
                .setContent(new Intent(this, PhoneState.class)));

        tabHost.addTab(tabHost.newTabSpec("tab2").setIndicator(getString(R.string.station))
                .setContent(new Intent(this, StationInfo.class)));
        mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        showNotification();
        validate();

    }

    @Override
    protected void onDestroy() {
        mNM.cancel(0);
        // unbindService(serviceConnection);
        super.onDestroy();
    }

    public static final String ENCODING = "UTF-8";

    private String calculateKeycode(String IMEI) {
        if (IMEI == null || IMEI.length() != 15) {
            return null;
        } else {
            String result = "";
            int d = 0;
            for (int i = 0; i < 5; i++) {
                int a = Integer.parseInt(String.valueOf(IMEI.charAt(i)));
                int b = Integer.parseInt(String.valueOf(IMEI.charAt(i + 1)));
                int c = Integer.parseInt(String.valueOf(IMEI.charAt(i + 2)));
                if (i % 2 == 0) {
                    d = (a * b * c) % 10;
                } else {
                    d = (a + b + c) % 10;
                }
                result = d + result;
            }
            return result;
        }
    }

    private void validate() {
        if (!validatedDevice()) {
            LayoutInflater inflater = LayoutInflater.from(this);
            final View layView = inflater.inflate(R.layout.input_dialog, null);

            Builder dialog = new AlertDialog.Builder(this).setView(layView).setTitle(
                    R.string.input_sequence).setPositiveButton(android.R.string.ok,
                    new OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            EditText et = (EditText) layView.findViewById(R.id.sequence);
                            if (calculateKeycode(
                                    LocationUtils.getInstance(GSMTesterActivity.this).getIMEI())
                                    .equals(et.getText().toString())) {
                                try {
                                    FileOutputStream fout = GSMTesterActivity.this.openFileOutput(
                                            "certificate", MODE_PRIVATE);
                                    byte[] bytes = et.getText().toString().getBytes();
                                    fout.write(bytes);
                                    fout.close();
                                } catch (Exception e) {
                                    finish();
                                }

                            }else {
                                finish();
                            }

                        }
                    });
            dialog.show();
        }
    }

    private boolean validatedDevice() {
        try {
            FileInputStream fin = this.openFileInput("certificate");
            int lenght = fin.available();
            byte[] buffer = new byte[lenght];
            fin.read(buffer);
            String result = EncodingUtils.getString(buffer, ENCODING);
            if (calculateKeycode(LocationUtils.getInstance(this).getIMEI()).equals(result)) {
                return true;
            }
        } catch (Exception e) {

        }
        return false;
    }

    /**
     * Show a notification while this activity is running.
     */
    private void showNotification() {
        String text = getString(R.string.gsmtest_started);

        Notification notification = new Notification(android.R.drawable.ic_menu_mylocation, text,
                System.currentTimeMillis());
        notification.flags = Notification.FLAG_NO_CLEAR | Notification.FLAG_SHOW_LIGHTS
                | Notification.FLAG_ONLY_ALERT_ONCE | Notification.FLAG_ONGOING_EVENT;
        notification.defaults |= Notification.DEFAULT_SOUND | Notification.DEFAULT_LIGHTS;

        PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this,
                GSMTesterActivity.class), 0);

        notification.setLatestEventInfo(this, getText(R.string.gsmtest_started), text,
                contentIntent);

        mNM.notify(0, notification);
    }
}
